package com.metagurukul.informer.service;

import java.sql.SQLException;
import java.util.*;

import com.metagurukul.informer.dao.QuestionTagMappingDAO;
import com.metagurukul.informer.dao.QuestionsDAO;
import com.metagurukul.informer.dao.TagDAO;
import com.metagurukul.informer.valueObjects.Questions;

/**
 * Class QuestionService to handle functions related to the questions
 * @author
 *
 */
public class QuestionsService {
	
	/**
	 * ...Method to get all the questions from database layer
	 * @return list of questions
	 */
	public ArrayList<Questions> getQuestions() throws SQLException {
		ArrayList<Questions> listOfQuestions =  new QuestionsDAO().getAllQuestions();
	    return listOfQuestions;
	}
	
	/**
	 * ...Method for for all the question fields to the questionDAO for the insertion
	 * @param title
	 * @param description
	 * @param tags
	 * @param user_id
	 * @param context
	 * @return
	 */
	public int insert(String title, String description, String tags, String user_id) throws SQLException{
	   QuestionsDAO dao=new QuestionsDAO();
	   
	   /*
	    * calling the insert function of DAO
	    * getting the id of the new inserted question
	    */
	   int question_id=dao.insert(new Questions(0,title,description,false,user_id,null));
	   String tag[]=tags.split(",");
	   TagDAO tagDAO=new TagDAO();
	   QuestionTagMappingDAO questionTagMappingDAO= new QuestionTagMappingDAO();
	   
	   /*
	    * Calling insert tag_question_mapping for each tag of question
	    */
	   Set<String> set=new HashSet<String>();
	   for(String temp:tag){
		   if(!temp.trim().equals("")){
			   if(temp.trim().length()>20)
				   continue;
			   if(set.add(temp.trim())){
				   int tag_id=tagDAO.findTagId(temp.trim());
				   questionTagMappingDAO.insert(question_id,tag_id);   
			   }
		   }
	   }
	   return question_id;
	}
	
	/**
	 * ...Method to delete a question by calling the DAO function
	 * @param id
	 * @param context
	 * @return
	 */
	public boolean deleteQuestion(int id)  throws SQLException{
		QuestionsDAO questionsdao = new QuestionsDAO ();
		return questionsdao.DeleteById(id);
	}
}
